import type { AppRouteModule, AppRouteRecordRaw } from '/@/router/types'
import type { Router, RouteRecordNormalized } from 'vue-router'

import { getParentLayout, LAYOUT, EXCEPTION_COMPONENT } from '/@/router/constant'
import { cloneDeep, omit } from 'lodash-es'
import { warn } from '/@/utils/log'
import { createRouter, createWebHashHistory } from 'vue-router'

export type LayoutMapKey = 'LAYOUT'
const IFRAME = () => import('/@/views/sys/iframe/FrameBlank.vue')

const LayoutMap = new Map<string, () => Promise<typeof import('*.vue')>>()

LayoutMap.set('LAYOUT', LAYOUT)
LayoutMap.set('IFRAME', IFRAME)

let dynamicViewsModules: Record<string, () => Promise<Recordable>>

// Dynamic introduction
function asyncImportRoute(routes: AppRouteRecordRaw[] | undefined) {
  dynamicViewsModules = dynamicViewsModules || import.meta.glob('../../views/**/*.{vue,tsx}')
  if (!routes) return
  routes.forEach(item => {
    if (!item.component && item.meta?.frameSrc) {
      item.component = 'IFRAME'
    }
    const { component, name } = item
    const { children } = item
    if (component) {
      const layoutFound = LayoutMap.get(component.toUpperCase())
      if (layoutFound) {
        item.component = layoutFound
      } else {
        item.component = dynamicImport(dynamicViewsModules, component as string)
      }
    } else if (name) {
      item.component = getParentLayout()
    }
    children && asyncImportRoute(children)
  })
}

function dynamicImport(
  dynamicViewsModules: Record<string, () => Promise<Recordable>>,
  component: string
) {
  const keys = Object.keys(dynamicViewsModules)
  const matchKeys = keys.filter(key => {
    const k = key.replace('../../views', '')
    const startFlag = component.startsWith('/')
    const endFlag = component.endsWith('.vue') || component.endsWith('.tsx')
    const startIndex = startFlag ? 0 : 1
    const lastIndex = endFlag ? k.length : k.lastIndexOf('.')
    return k.substring(startIndex, lastIndex) === component
  })
  if (matchKeys?.length === 1) {
    const matchKey = matchKeys[0]
    return dynamicViewsModules[matchKey]
  } else if (matchKeys?.length > 1) {
    warn(
      'Please do not create `.vue` and `.TSX` files with the same file name in the same hierarchical directory under the views folder. This will cause dynamic introduction failure'
    )
    return
  } else {
    warn('在src/views/下找不到`' + component + '.vue` 或 `' + component + '.tsx`, 请自行创建!')
    return EXCEPTION_COMPONENT
  }
}

// Turn background objects into routing objects
export function transformObjToRoute<T = AppRouteModule>(routeList: AppRouteModule[]): T[] {
  routeList.forEach(route => {
    const component = route.component as string
    if (component) {
      if (component.toUpperCase() === 'LAYOUT') {
        route.component = LayoutMap.get(component.toUpperCase())
      } else {
        route.children = [cloneDeep(route)]
        route.component = LAYOUT
        route.name = `${route.name}Parent`
        route.path = ''
        const meta = route.meta || {}
        meta.single = true
        meta.affix = false
        route.meta = meta
      }
    } else {
      warn('请正确配置路由：' + route?.name + '的component属性')
    }
    route.children && asyncImportRoute(route.children)
  })
  return routeList as unknown as T[]
}

// 补充菜单
export function supplementMenu(routeList) {
  routeList.data.sort((a, b) => a.orderNum - b.orderNum)
  const naemList = [
    // 'teacherDetail',
    'ReviewPaper',
    // 'examPapersDetail',
    // 'indexExaminaTionPaper',
    // 'Examinationestpaper',
    'FractionDetaile',
    // 'TeacherChoice',
    'modifyStructure',
  ]
  const eleObj: any = {
    modifyStructure: {
      autoId: 177,
      pid: 0,
      title: '试题结构编辑',
      titleCn: '试题结构编辑',
      orderNum: 1,
      path: '/examination-audit/modifyStructure',
      component: '/examination-audit/abnormal-teacher/modifyStructure',
      icon: 'ci:dot-05-xl',
      hidden: true,
      hiddenChildren: true,
      redirect: '',
      metaJson: '',
      menuType: 'catalogue',
      handMethod: '',
      state: 'normal',
      remark: '',
      hideBreadcrumb: null,
      currentActiveMenu: '',
      ifLink: null,
      takeToken: 'n',
      frameSrc: '',
      name: 'modifyStructure',
      meta: {
        icon: 'ci:dot-05-xl',
        hideChildrenInMenu: true,
        hideMenu: true,
        title: '教师评阅详情',
        currentActiveMenu: '',
        hideBreadcrumb: null,
        frameSrc: '',
      },
      children: null,
    },
    // teacherDetail: {
    //   autoId: 31,
    //   pid: 0,
    //   title: '教师评阅详情',
    //   titleCn: '教师评阅详情',
    //   orderNum: 1,
    //   path: 'detail',
    //   component: '/management/teacher/detail',
    //   icon: 'ci:dot-05-xl',
    //   hidden: true,
    //   hiddenChildren: true,
    //   redirect: '',
    //   metaJson: '',
    //   menuType: 'catalogue',
    //   handMethod: '',
    //   state: 'normal',
    //   remark: '',
    //   hideBreadcrumb: null,
    //   currentActiveMenu: '',
    //   ifLink: null,
    //   takeToken: 'n',
    //   frameSrc: '',
    //   name: 'teacherDetail',
    //   meta: {
    //     icon: 'ci:dot-05-xl',
    //     hideChildrenInMenu: true,
    //     hideMenu: true,
    //     title: '教师评阅详情',
    //     currentActiveMenu: '',
    //     hideBreadcrumb: null,
    //     frameSrc: '',
    //   },
    //   children: null,
    // },
    ReviewPaper: {
      autoId: 32,
      pid: 0,
      title: '试题评阅详情',
      titleCn: '试题评阅详情',
      orderNum: 2,
      path: 'review-paper',
      component: '/exam-info/review-paper/index',
      icon: 'ci:dot-05-xl',
      hidden: true,
      hiddenChildren: true,
      redirect: '',
      metaJson: '',
      menuType: 'catalogue',
      handMethod: '',
      state: 'normal',
      remark: '',
      hideBreadcrumb: null,
      currentActiveMenu: '',
      ifLink: null,
      takeToken: 'n',
      frameSrc: '',
      name: 'ReviewPaper',
      meta: {
        icon: 'ci:dot-05-xl',
        hideChildrenInMenu: true,
        hideMenu: true,
        title: '试题评阅详情',
        currentActiveMenu: '',
        hideBreadcrumb: null,
        frameSrc: '',
      },
      children: null,
    },
    // examPapersDetail: {
    //   autoId: 30,
    //   pid: 0,
    //   title: '科目评阅详情',
    //   titleCn: '科目评阅详情',
    //   orderNum: 1,
    //   path: 'subjecTdetail',
    //   component: '/management/paper/detail',
    //   icon: 'ci:dot-05-xl',
    //   hidden: true,
    //   hiddenChildren: true,
    //   redirect: '',
    //   metaJson: '',
    //   menuType: 'catalogue',
    //   handMethod: '',
    //   state: 'normal',
    //   remark: '',
    //   hideBreadcrumb: null,
    //   currentActiveMenu: '',
    //   ifLink: null,
    //   takeToken: 'n',
    //   frameSrc: '',
    //   name: 'examPapersDetail',
    //   meta: {
    //     icon: 'ci:dot-05-xl',
    //     hideChildrenInMenu: true,
    //     hideMenu: true,
    //     title: '科目评阅详情',
    //     currentActiveMenu: '',
    //     hideBreadcrumb: null,
    //     frameSrc: '',
    //   },
    //   children: null,
    // },
    // indexExaminaTionPaper: {
    //   autoId: 13,
    //   pid: 0,
    //   title: '考卷信息',
    //   titleCn: '考卷信息',
    //   orderNum: 4,
    //   path: 'examination-paper',
    //   component: '/organizationalManagement/examinationPaper/index',
    //   icon: 'ci:dot-05-xl',
    //   hidden: true,
    //   hiddenChildren: true,
    //   redirect: '',
    //   metaJson: '',
    //   menuType: 'catalogue',
    //   handMethod: '',
    //   state: 'normal',
    //   remark: '',
    //   hideBreadcrumb: null,
    //   currentActiveMenu: '',
    //   ifLink: null,
    //   takeToken: 'n',
    //   frameSrc: '',
    //   name: 'indexExaminaTionPaper',
    //   meta: {
    //     icon: 'ci:dot-05-xl',
    //     hideChildrenInMenu: true,
    //     hideMenu: true,
    //     title: '考卷信息',
    //     currentActiveMenu: '',
    //     hideBreadcrumb: null,
    //     frameSrc: '',
    //   },
    //   children: [],
    // },
    // Examinationestpaper: {
    //   autoId: 29,
    //   pid: 0,
    //   title: '试卷信息',
    //   titleCn: '试卷信息',
    //   orderNum: 1,
    //   path: 'examination-testpaper',
    //   component: '/organizationalManagement/examinationPaper/testpaper',
    //   icon: 'ci:dot-05-xl',
    //   hidden: true,
    //   hiddenChildren: true,
    //   redirect: '',
    //   metaJson: '',
    //   menuType: 'catalogue',
    //   handMethod: '',
    //   state: 'normal',
    //   remark: '',
    //   hideBreadcrumb: null,
    //   currentActiveMenu: '',
    //   ifLink: null,
    //   takeToken: 'n',
    //   frameSrc: '',
    //   name: 'Examinationestpaper',
    //   meta: {
    //     icon: 'ci:dot-05-xl',
    //     hideChildrenInMenu: true,
    //     hideMenu: true,
    //     title: '试卷信息',
    //     currentActiveMenu: '',
    //     hideBreadcrumb: null,
    //     frameSrc: '',
    //   },
    //   children: null,
    // },
    FractionDetaile: {
      autoId: 33,
      pid: 0,
      title: '试卷还原',
      titleCn: '试卷还原',
      orderNum: 1,
      path: 'fraction-etaile',
      component: '/examineGrade/fraction/detaile',
      icon: 'ci:dot-05-xl',
      hidden: true,
      hiddenChildren: true,
      redirect: '',
      metaJson: '',
      menuType: 'catalogue',
      handMethod: '',
      state: 'normal',
      remark: '',
      hideBreadcrumb: null,
      currentActiveMenu: '',
      ifLink: null,
      takeToken: 'n',
      frameSrc: '',
      name: 'FractionDetaile',
      meta: {
        icon: 'ci:dot-05-xl',
        hideChildrenInMenu: true,
        hideMenu: true,
        title: '试卷还原',
        currentActiveMenu: '',
        hideBreadcrumb: null,
        frameSrc: '',
      },
      children: null,
    },
    // TeacherChoice: {
    //   autoId: 33,
    //   pid: 0,
    //   title: '选择题检查',
    //   titleCn: '选择题检查',
    //   orderNum: 1,
    //   path: 'teacher-choice',
    //   component: '/teacher/choice/index',
    //   icon: 'ci:dot-05-xl',
    //   hidden: true,
    //   hiddenChildren: true,
    //   redirect: '',
    //   metaJson: '',
    //   menuType: 'catalogue',
    //   handMethod: '',
    //   state: 'normal',
    //   remark: '',
    //   hideBreadcrumb: null,
    //   currentActiveMenu: '',
    //   ifLink: null,
    //   takeToken: 'n',
    //   frameSrc: '',
    //   name: 'TeacherChoice',
    //   meta: {
    //     icon: 'ci:dot-05-xl',
    //     hideChildrenInMenu: true,
    //     hideMenu: true,
    //     title: '选择题检查',
    //     currentActiveMenu: '',
    //     hideBreadcrumb: null,
    //     frameSrc: '',
    //   },
    //   children: null,
    // },
  }
  function seleList(list) {
    if (!list) return []
    for (let i = 0; i < list.length; i++) {
      if (list[i].children && list[i].children.length) {
        //编辑按钮列表
        if (!list[i]?.meta) {
          list[i].meta = {}
        }
        list[i].meta.buttonList = []
        for (let b = 0; b < list[i].children.length; b++) {
          if (list[i].children[b].menuType == 'button') {
            list[i].meta.buttonList.push(list[i].children[b].name)
          }
        }
      }
      // if (list[i].name == 'ExaminationPaper') {
      //   eleObj['indexExaminaTionPaper'] = JSON.parse(JSON.stringify(list[i]))
      //   eleObj['indexExaminaTionPaper'].name = 'indexExaminaTionPaper'
      //   eleObj['indexExaminaTionPaper'].meta.hideMenu = true
      // }
      if (naemList.includes(list[i].name)) {
        eleObj[list[i].name] = JSON.parse(JSON.stringify(list[i]))
        list.splice(i, 1)
        i--
      } else if (list[i].children && list[i].children.length) {
        list[i].children = seleList(list[i].children)
      } else if (!list[i].redirect && !list[i].hiddenChildren) {
        list[i].redirect = `${list[i].path}/index`
      }

    }
    return list
  }

  seleList(routeList.data)
  if (routeList.data) {
    for (let key in eleObj) {
      routeList.data.push(eleObj[key])
    }
  }

  return routeList
}

/**
 * Convert multi-level routing to level 2 routing
 */
export function flatMultiLevelRoutes(routeModules: AppRouteModule[]) {
  const modules: AppRouteModule[] = cloneDeep(routeModules)
  for (let index = 0; index < modules.length; index++) {
    const routeModule = modules[index]
    if (!isMultipleRoute(routeModule)) {
      continue
    }
    promoteRouteLevel(routeModule)
  }
  return modules
}

// Routing level upgrade
function promoteRouteLevel(routeModule: AppRouteModule) {
  // Use vue-router to splice menus
  let router: Router | null = createRouter({
    routes: [routeModule as unknown as RouteRecordNormalized],
    history: createWebHashHistory(),
  })

  const routes = router.getRoutes()
  addToChildren(routes, routeModule.children || [], routeModule)
  router = null

  routeModule.children = routeModule.children?.map(item => omit(item, 'children'))
}

// Add all sub-routes to the secondary route
function addToChildren(
  routes: RouteRecordNormalized[],
  children: AppRouteRecordRaw[],
  routeModule: AppRouteModule
) {
  for (let index = 0; index < children.length; index++) {
    const child = children[index]
    const route = routes.find(item => item.name === child.name)
    if (!route) {
      continue
    }
    routeModule.children = routeModule.children || []
    if (!routeModule.children.find(item => item.name === route.name)) {
      routeModule.children?.push(route as unknown as AppRouteModule)
    }
    if (child.children?.length) {
      addToChildren(routes, child.children, routeModule)
    }
  }
}

// Determine whether the level exceeds 2 levels
function isMultipleRoute(routeModule: AppRouteModule) {
  if (!routeModule || !Reflect.has(routeModule, 'children') || !routeModule.children?.length) {
    return false
  }

  const children = routeModule.children

  let flag = false
  for (let index = 0; index < children.length; index++) {
    const child = children[index]
    if (child.children?.length) {
      flag = true
      break
    }
  }
  return flag
}
